package com.example.hello;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.Settings;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry.Registrar;

import com.example.hello.R;
import com.example.hello.jni.DataBus;

/**
 * HelloPlugin
 */
public class HelloPlugin implements MethodCallHandler {
    private Activity mActivity;
    private DataBus dataBus;
    private ByteBuffer byteBuffer;

    /**
     * Plugin registration.
     */
    public HelloPlugin(Activity activity) {
        mActivity = activity;
        dataBus = new DataBus();
    }

    public static void registerWith(Registrar registrar) {
        final MethodChannel channel = new MethodChannel(registrar.messenger(), "hello");
        channel.setMethodCallHandler(new HelloPlugin(registrar.activity()));
    }

    @Override
    public void onMethodCall(MethodCall call, Result result) {
        if (call.method.equals("getPlatformVersion")) {
            result.success("Android " + dataBus.stringFromJNI());
        } else if (call.method.equals("getNativeImage")) {
            int type = call.argument("type");
            if (type == 1) {
                result.success(getRaw());
            } else if (type == 2) {
                result.success(getDrawable());
            }
        } else if (call.method.equals("getNativeImagePtr")) {
            result.success(getRawImagePtr());
        } else if (call.method.equals("getBitmapPtr")) {
            result.success(getBitmapPtr());
        } else if (call.method.equals("callCMethod")) {
            dataBus.callJavaMethod();
            result.success(null);
        } else if (call.method.equals("threadMethod")) {
            dataBus.threadMethod();
            result.success(null);
        } else if (call.method.equals("tmpTest")) {
            Intent in = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
            in.setData(Uri.fromParts("package", mActivity.getPackageName(), null));
            mActivity.startActivity(in);//直接跳转到设置界面
            result.success(null);
        } else {
            result.notImplemented();
        }
    }

    private byte[] getRaw() {
        try {
            int resId = R.raw.cat;
            InputStream inputStream = mActivity.getResources().openRawResource(resId);
            //从inputStream种读取资源，转成bytes
            int size = 0;
            size = inputStream.available();

            byte[] bytes = new byte[size];
            byte[] buffer = new byte[Math.min(1024, size)];
            int index = 0;
            int len = inputStream.read(buffer);//读取资源到byte[]
            while (len != -1) {
                System.arraycopy(buffer, 0, bytes, index, len);
                index += len;
                len = inputStream.read(buffer);
            }
            inputStream.close();
            return bytes;
        } catch (IOException e) {
            e.printStackTrace();
            return new byte[0];
        }
    }

    // 获取图片的内存指针(TODO flutter层暂不可用！！！！)
    private Map<String, Object> getRawImagePtr() {
        try {
            int resId = R.raw.ic_launcher;
            InputStream inputStream = mActivity.getResources().openRawResource(resId);
            int size = inputStream.available();
            byteBuffer = ByteBuffer.allocateDirect(size);
            long ptr = dataBus.getByteBufferPtr(byteBuffer);
            Map<String, Object> reply = new HashMap<String, Object>();
            reply.put("rawDataAddress", ptr);
            reply.put("rawDataLength", size);
            inputStream.close();
            return reply;
        } catch (IOException e) {
            e.printStackTrace();
            return new HashMap<String, Object>();
        }
    }

    // 获取图片的内存指针
    private Map<String, Object> getBitmapPtr() {
        try {
            int resId2 = R.drawable.shuai;
            Bitmap bmp = BitmapFactory.decodeResource(mActivity.getResources(), resId2);
            long ptr = dataBus.getBitmapPixelDataMemoryPtr(bmp);
            Map<String, Object> reply = new HashMap<String, Object>();
            reply.put("pixelsDataAddress", ptr);
            reply.put("pixelsDataWidth", bmp.getWidth());
            reply.put("pixelsDataHeight", bmp.getHeight());
            return reply;
        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap<String, Object>();
        }
    }

    private byte[] getDrawable() {
        int resId2 = R.drawable.shuai;
        Bitmap bmp = BitmapFactory.decodeResource(mActivity.getResources(), resId2);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        return baos.toByteArray();
    }

    static {
        System.loadLibrary("native-lib");
    }
}
